//
//  MNDAssessWebViewController.m
//  minidai
//
//  Created by Vitas on 2018/7/11.
//  Copyright © 2018年 迷你贷. All rights reserved.
//

#import "MNDAssessWebViewController.h"
#import "SYWebLoadingProgress.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "RSAUtil.h"

#import "MNDCarBrandViewController.h"
#import "MNDSelectProvinceAndCityViewController.h"


NSString *const AssessHeadURL = API_TOOL_URL@"/browser/visit?url=";

@interface MNDAssessWebViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;
@property (strong, nonatomic) UIButton *closeButton;
@property (strong, nonatomic) SYWebLoadingProgress *webLoadingProgress;
@property (strong, nonatomic) JSContext *context;

@end

@implementation MNDAssessWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        //                self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [self initialWebView];
    
    [self initialBackButton];
    
    //设置堆栈控制器
    if (_isClearStack) {
        [self configStackController];
    }
    
    
    // Do any additional setup after loading the view.
}
- (void)updateWeb {

    self.webViewUrl = [NSString stringWithFormat:@"%@?car_id=%zd&car_name=%@&city_id=%zd&city_name=%@",API_CAR_ASSESS,self.carId,self.carName,self.cityAddressId,self.cityName];
    if ([MNDLoginUserModel isUserLogin]) {
        NSString *urlStr = [NSString stringWithFormat:@"%@%@", AssessHeadURL, [NSString urlEncodeStr:self.webViewUrl]];
        NSLog(@"url: %@", urlStr);
        NSURL *url = [NSURL URLWithString: urlStr];
        NSURLRequest *request = [self configRequestHeaderFileds:url];
        
        [self.webView loadRequest:request];
    } else {
        NSString *urlStr = [NSString stringWithFormat:@"%@%@", AssessHeadURL, [NSString urlEncodeStr:self.webViewUrl]];
        NSLog(@"url: %@", urlStr);
        NSURL *url = [NSURL URLWithString: urlStr];
        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60.0];
        [self.webView loadRequest:request];
    }
    
}


- (void) initialWebView {
    
    self.webView = [[UIWebView alloc] init];
    self.webView.backgroundColor = kColorBackground;
    self.webView.scrollView.bounces = NO;
    //    self.webView.detectsPhoneNumbers = NO;
    
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    self.webView.scalesPageToFit = YES;
    self.webView.delegate = self;
    
    if ([MNDLoginUserModel isUserLogin]) {
        NSString *urlStr = [NSString stringWithFormat:@"%@%@", AssessHeadURL, [NSString urlEncodeStr:self.webViewUrl]];
        NSLog(@"url: %@", urlStr);
        NSURL *url = [NSURL URLWithString: urlStr];
        NSURLRequest *request = [self configRequestHeaderFileds:url];
        
        [self.webView loadRequest:request];
    } else {
        NSString *urlStr = [NSString stringWithFormat:@"%@%@", AssessHeadURL, [NSString urlEncodeStr:self.webViewUrl]];
        NSLog(@"url: %@", urlStr);
        NSURL *url = [NSURL URLWithString: urlStr];
        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60.0];
        [self.webView loadRequest:request];
    }
//    NSString *encodStr = [self.webViewUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSURL *url = [NSURL URLWithString: encodStr];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60.0];
//    [self.webView loadRequest:request];
    [self.view beginLoading];
    
}

- (void)initialBackButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    self.closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.closeButton setTitle:@"关闭" forState:UIControlStateNormal];
    self.closeButton.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [self.closeButton setTitleColor:[UIColor colorWithRed:57/255.0 green:66/255.0 blue:64/255.0 alpha:1.0] forState:UIControlStateNormal];
    [self.closeButton addTarget:self action:@selector(closeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.closeButton setFrame:CGRectMake(0, 0, 40, 30)];
    [self.closeButton setHidden:YES];
    
    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithCustomView:self.closeButton];
    //    [closeItem setTintColor: [UIColor colorWithRed:57/255.0 green:66/255.0 blue:64/255.0 alpha:1.0]];
    
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItems = @[backBarButtonItem, closeItem];;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem, closeItem];
    }
}

- (void)backAction:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
    [self clearWebViewCookies];
}

- (void)closeAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
    
    [self clearWebViewCookies];
}

- (NSMutableURLRequest *)configRequestHeaderFileds: (NSURL *)url {
    // 添加请求头信息
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60.0];
    
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    NSString *userCode = [self rsaEncode: user.user_code];
    
    [request setValue:userCode forHTTPHeaderField:@"USERCODE"];
    
    return request;
}

- (NSString *)rsaEncode:(NSString *)rsaStr {
    NSString *encryText = [RSAUtil encryptString:[NSString stringWithFormat:@"%@", rsaStr] publicKey:RSA_PUBLIC_KEY];
    NSString *unreserved = @"";
    NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
    [allowed addCharactersInString:unreserved];
    
    NSString *encodeEncryText = [encryText stringByAddingPercentEncodingWithAllowedCharacters:allowed];
    
    return encodeEncryText;
}

- (void)configStackController {
    NSArray *arrayVC = self.navigationController.viewControllers;
    self.navigationController.viewControllers = @[arrayVC[0],arrayVC[1],arrayVC[3]];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    NSString *absoluteStr = request.URL.absoluteString;
    NSLog(@"absoluteStr:%@",absoluteStr);
    return YES;
}

- (SYWebLoadingProgress *)webLoadingProgress {
    if (!_webLoadingProgress) {
        _webLoadingProgress = [[SYWebLoadingProgress alloc] init];
        _webLoadingProgress.progressColor = kColorBlue;
        _webLoadingProgress.progressStyle = LoadingPregressType_Noraml;
    }
    
    if ([self.navigationController.navigationBar isHidden]) {
        _webLoadingProgress.frame = CGRectMake(0, 20, kScreenWidth, 2);
        
    } else {
        
        CGFloat yPosition = 0.0;
        //        if (kScreenHeight >= 812) {
        //            yPosition = 24;
        //        }
        _webLoadingProgress.frame = CGRectMake(0, yPosition, kScreenWidth, 2);
        //        [self.view.layer insertSublayer:_webLoadingProgress atIndex:0];
    }
    [self.webView.layer addSublayer:_webLoadingProgress];
    
    return _webLoadingProgress;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    
    [self.webLoadingProgress startProgressAnimation];
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    [self.webLoadingProgress completedProgressAnimation];
    //    取消长按webView上的链接弹出actionSheet的问题
    [webView stringByEvaluatingJavaScriptFromString: @"document.documentElement.style.webkitUserSelect='none';"];

    //初始化context
    kdeclare_weakself;
    self.context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.context[@"selectCarTypeAction"] = ^(NSString *str) {
        MNDCarBrandViewController *brandVC = [UIStoryboard viewControllerWithIdentifier:@"MNDCarBrandViewController"];
        brandVC.isWebEnter = YES;
        brandVC.carTypeBlock = ^(NSString *carType, NSInteger typeId) {
            weakSelf.carName = carType;
            weakSelf.carId = typeId;
            [weakSelf updateWeb];
        };
        [weakSelf.navigationController pushViewController:brandVC animated:YES];
    };
    
    self.context[@"selectAreaAction"] = ^(NSString *str) {
        MNDSelectProvinceAndCityViewController *brandVC = [UIStoryboard viewControllerWithIdentifier:@"MNDSelectProvinceAndCityViewController"];
        brandVC.isWebEnter = YES;
        brandVC.addressAndIdBlock = ^(NSString *provinceStr, NSString *cityStr, NSInteger addressId) {
            weakSelf.cityName = cityStr;
            weakSelf.cityAddressId = addressId;
            [weakSelf updateWeb];
        };
        [weakSelf.navigationController pushViewController:brandVC animated:YES];
    };
    [self.view endLoading];
    
}


- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [self.view endLoading];
    [self.webLoadingProgress completedProgressAnimation];
    if (error.code == -999) {
        return;
    }
    
    if (error.code == 102) {
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController setNavigationBarHidden:NO animated:NO];
    });
    
    NSLog(@"error: %@", error);
    
    [NetworkProgressHUD showHudNetworkError:error];
    WeakSelf(self);
    SYBlankPageType blankType = [self.view blankPageTypeWithError:error];
    [self.view configBlankPage:blankType hasData:NO reloadButtonBlock:^(id sender) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakself.webView reload];
            [weakself.view beginLoading];
        });
        
    }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)clearWebViewCookies {
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
    //缓存web清除
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
